
#import "PywBaseViewController.h"
#import "UIBarButtonItem+Pyw.h"
#import "UIView+Pyw.h"
#import "UIImage+Pyw.h"
#import "UIColor+Pyw.h"
#import "PywAppInfo.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywPayViewController.h"
#import "PywSdk+pay.h"
#import "PywCPNotifications.h"
#import "PywPaymentInfo.h"

@interface PywBaseViewController ()<UIGestureRecognizerDelegate>

@end

@implementation PywBaseViewController

@synthesize showBack;

#pragma mark - Init
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

#pragma mark - Lift Cycle Method
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self viewAppearance];
}
- (void)viewAppearance
{
    self.view.backgroundColor = [UIColor colorWithRed:(255)/255.0 green:(255)/255.0 blue:255/(255.0) alpha:1.0];
    [UIApplication sharedApplication].statusBarHidden = YES;
    
    
    NSString *imgName = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?@"logo01":@"img_logo";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:imgName
                                                                           highImageName:nil
                                                                            locationType:NO
                                                                                  target:self
                                                                                  action:nil];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"icon_return_normal"
                                                                           highImageName:nil
                                                                            locationType:YES
                                                                                  target:self
                                                                                  action:@selector(returnback)];
    [self.navigationItem.leftBarButtonItem setAccessibilityIdentifier:@"common_back"];
    [self.navigationItem.titleView setAccessibilityIdentifier:@"common_title"];
}

- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    [self setupOrientation];
    
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    if (_editingField != nil) {
        [_editingField resignFirstResponder];
    }
    
    [super viewWillDisappear:animated];
}

#pragma mark - OrientationChange Method
// viewWillAppear调用,通过状态栏方向选取布局
- (void)setupOrientation {
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if (orientation == UIInterfaceOrientationPortrait ) {
        _orientation = UIInterfaceOrientationPortrait;
        [self verticalScreenControlsDistribution];
        
        return;
        
    } else if (orientation == UIInterfaceOrientationLandscapeLeft ) {
        
        _orientation = UIInterfaceOrientationLandscapeLeft;
        
        [self horizontalScreenControlsDistribution];
        
        return;
        
    } else if (orientation == UIInterfaceOrientationLandscapeRight) {
        
        _orientation = UIInterfaceOrientationLandscapeRight;
        
        [self horizontalScreenControlsDistribution];
        
        return;
        
    } else {
        _orientation = UIInterfaceOrientationPortraitUpsideDown;
        [self verticalScreenControlsDistribution];
        
        return;
    }
}

// 屏幕方向改变时调用
- (void)orientationChange {
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if (_orientation == orientation) return; //方向一致则不做操作
    
    [self screenRotationMethod:orientation];
    
}

- (void)screenRotationMethod:(UIInterfaceOrientation) orientation
{
    
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
        _orientation = orientation;
        
        [self verticalScreenControlsDistribution];
    }else{
        _orientation = orientation;
        
        [self horizontalScreenControlsDistribution];
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
#pragma mark - Interface Method
// 竖屏布局
- (void)verticalScreenControlsDistribution {
    
}

// 横屏布局
- (void)horizontalScreenControlsDistribution {
    
}


#pragma mark - Private Method
- (void)returnback
{
    [PywMBProgressHUD hideHUD];
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


- (BOOL)isRootViewController
{
    return (self == self.navigationController.viewControllers.firstObject);
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([self isRootViewController]) {
        return NO;
    } else {
        return YES;
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    _editingField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [textField resignFirstResponder];
    _editingField = nil;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - keyBoard Notification
- (void)keyboardShow:(NSNotification *)notification {
    
    if (_editingField != nil) {
        
        CGFloat keyboardHeight = [self keyBoardHeight:notification];
        
        CGFloat edtingFieldMaxY = CGRectGetMaxY(_editingField.frame);
        
        CGFloat height = self.height;
        
        if (edtingFieldMaxY < height - keyboardHeight) return;
        
        
        CGFloat deltaY = edtingFieldMaxY - (height - keyboardHeight - 10);
        if (!iOS7) {
            deltaY += self.navigationController.navigationBar.frame.size.height;
            
        }
        [UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            self.view.y -= deltaY;
            
        } completion:nil];
    }
}

- (void)keyboardHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.view.y  = 0;
    } completion:nil];
}

- (CGFloat)keyBoardHeight:(NSNotification *)notification {
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        return keyboardRect.size.height;
    } else {
        return iOS8 ? keyboardRect.size.height:keyboardRect.size.width;
    }
}

#pragma mark - Set InterfaceOrientations
// 开启自动旋转
- (BOOL)shouldAutorotate {
    return YES;
}
// iOS9 支持横屏时，必须实现该方法
- (BOOL)prefersStatusBarHidden {
    return YES;
}
// 支持屏幕显示
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    if ([self supportedOrientation]) {
        return UIInterfaceOrientationMaskLandscape;
    }else{
        return UIInterfaceOrientationMaskPortrait;
    }
}
// 一开始的方向 , 即默认方向
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    if ([self supportedOrientation]) {
        return (UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight);
    }else{
        return UIInterfaceOrientationPortrait;
    }
}
/// 判断应用支持的屏幕方向
- (BOOL)supportedOrientation{
    /*
     iPhone屏幕方向
     UISupportedInterfaceOrientations = (
                                        UIInterfaceOrientationPortrait,
                                        UIInterfaceOrientationLandscapeLeft,
                                        UIInterfaceOrientationLandscapeRight
                                        );
     iPad屏幕方向
     "UISupportedInterfaceOrientations~ipad" = (
                                                UIInterfaceOrientationPortrait,
                                                UIInterfaceOrientationPortraitUpsideDown,
                                                UIInterfaceOrientationLandscapeLeft,
                                                UIInterfaceOrientationLandscapeRight
                                               );
     */
    
    // 判断数组是否包含某个元素
    NSArray *orientations = [self appSupportOrientations];
    if (orientations.count == 0) {
        return YES;
    }
    
    return ([orientations containsObject: @"UIInterfaceOrientationLandscapeLeft"]
            || [orientations containsObject:@"UIInterfaceOrientationLandscapeRight"]);
}

/// 获取app支持的屏幕方向数组
- (NSArray *)appSupportOrientations
{
    // 应用支持的屏幕方向
    NSArray *appSupportOrientations = [NSArray array];
    
    // 获取info.plist文件配置
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:bundlePath];
//    NSLog(@"dict===%@",dict);
    
    NSString *key = @"UISupportedInterfaceOrientations";
    appSupportOrientations = [dict objectForKey:key];
    
    return appSupportOrientations;
}

#pragma mark - popViewController
- (void)popView {
    // 回到上一级
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)popRootView {
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        [self popRootViewCompletion];
    }];
}

- (void)popRootViewCompletion {
    
}

#pragma mark - Setter & Getter
- (void)setShowBack:(BOOL)showback {
    if(showback){
        
    }else{
        
        self.navigationItem.hidesBackButton = YES;
    }
}

- (CGFloat)v_height {
    return [UIScreen mainScreen].bounds.size.height > [UIScreen mainScreen].bounds.size.width ? [UIScreen mainScreen].bounds.size.height : [UIScreen mainScreen].bounds.size.width;
}

- (CGFloat)v_width {
    return [UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height ? [UIScreen mainScreen].bounds.size.width : [UIScreen mainScreen].bounds.size.height;
}

- (CGFloat)h_width {
    return ([UIScreen mainScreen].bounds.size.width <[UIScreen mainScreen].bounds.size.height ? [UIScreen mainScreen].bounds.size.height : [UIScreen mainScreen].bounds.size.width);
}

- (CGFloat)h_height {
    return [UIScreen mainScreen].bounds.size.height >[UIScreen mainScreen].bounds.size.width ? [UIScreen mainScreen].bounds.size.width : [UIScreen mainScreen].bounds.size.height;
}

/**
 *  通过状态栏方向判断屏幕宽(iOS7以下无论横竖屏，都返回竖屏状态下的宽)
 *
 *  @return 返回当前屏幕的宽
 */

- (CGFloat)width {
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        return self.v_width;
    } else {
        return self.h_width;
    }
}

/**
 *  通过状态栏方向判断屏幕高(iOS7以下无论横竖屏，都返回竖屏状态下的高)
 *
 *  @return 返回当前屏幕的高
 */

- (CGFloat)height {
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        return self.v_height;
    } else {
        return self.h_height;
    }
}

/**
 *  iOS7以下，导航控制器中，view的Y从导航栏开始计算，而iOS7以上，从导航栏开始计算
 *
 *  @return 导航栏高度（view的初始Y值）
 */
- (CGFloat)navHeight {
    return iOS7 ? CGRectGetMaxY(self.navigationController.navigationBar.frame) : 0;
}


- (void)setupTitleView:(NSString *)title
{
    PywTitleView *titleView = [PywTitleView titleViewWithTitle:title];
    
    titleView.frame = CGRectMake(0, 0, self.navigationController.navigationBar.height + titleView.titleLabel.width, self.navigationController.navigationBar.height);
    
    self.navigationItem.titleView = titleView;
    
    self.titleView = titleView;
}


@end
